package com.sgb.net.util

import com.google.gson.JsonElement
import com.google.gson.JsonObject
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * 网络请求创建请求体工具类
 */
class RequestUtil private constructor(json: JsonObject? = null, map: HashMap<String, Any>? = null) {
    private val jsonType = "application/json"
    private val mJson: JsonObject? = json
    private val mMap: HashMap<String, Any>? = map

    companion object {
        @JvmStatic
        fun json(): RequestUtil = RequestUtil(json = JsonObject())

        @JvmStatic
        fun map(): RequestUtil = RequestUtil(map = HashMap())
    }

    fun add(key: String, value: Any?): RequestUtil {
        if (value == null) {
            return this
        }
        mJson?.run {
            when (value) {
                is String -> addProperty(key, value)
                is Number -> addProperty(key, value)
                is Boolean -> addProperty(key, value)
                is Char -> addProperty(key, value)
                is JsonElement -> add(key, value)
            }
        }
        mMap?.put(key, value)
        return this
    }

    /**
     * 创建json请求体
     */
    fun buildJsonBody(): RequestBody? {
        return mJson?.toString()?.toRequestBody(jsonType.toMediaTypeOrNull())
    }

    /**
     * 创建map请求体
     */
    fun buildMap(): HashMap<String, Any>? = mMap
}